package org.cc.media.player;


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.cc.media.vo.shoutcast.ShoutcastGenre;
import org.cc.media.vo.shoutcast.ShoutcastStation;
import org.cc.media.vo.shoutcast.ShoutcastStationList;

public class ShoutcastApiClient implements ApiClient {
	
	private static final String API_URL = "http://api.shoutcast.com";
	private static final String API_KEY = "sh19qvGfsOJkQ0pv";
	
	private ShoutcastPlaylistDigester digester = new ShoutcastPlaylistDigester();

	public static final void main(String[] args) {
		ShoutcastApiClient api = new ShoutcastApiClient();
		api.getStations("alternative");
	}
	
	@Override
	public List<ShoutcastGenre> getGenres() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<ShoutcastStation> getStations() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<ShoutcastStation> getStations(String genre) {
		List<ShoutcastStation> list2 = new ArrayList<ShoutcastStation>();
		CloseableHttpClient client = HttpClients.createDefault();
		String req = API_URL + "/legacy/genresearch?k=" + API_KEY + "&br=128&limit=10&genre=" + genre;
		System.out.println("Setting req to: " + req);
		HttpGet httpGet = new HttpGet(req);
		try {
			System.out.println();
			CloseableHttpResponse response1 = client.execute(httpGet);
			HttpEntity entity = response1.getEntity();
			String xml = EntityUtils.toString(entity);
			EntityUtils.consumeQuietly(entity);
			System.out.println(xml);
			
			JAXBContext jc = JAXBContext.newInstance(ShoutcastStationList.class);
	        Unmarshaller unmarshaller = jc.createUnmarshaller();
	        InputStream in = new ByteArrayInputStream(xml.getBytes("utf-8"));
	        ShoutcastStationList list = (ShoutcastStationList) unmarshaller.unmarshal(in);
	        list2 = (List<ShoutcastStation>) list.getStations();
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return list2;
	}

	@Override
	public List<ShoutcastStation> search(String keywords) {
		return null;
	}

	@Override
	public InputStream getStreamFromUrl(String url) {
		return digester.getStreamFromUrl(url);
	}

	@Override
	public InputStream getStreamFromId(String id) {
		return digester.getStreamFromId(id);
	}

}
